import {defineStore} from "pinia";
import { login,user } from "@/api/auth";

export interface IUserState{
    token:string;
    username:string;
    avatar:string;
    permissions:string[];
    info:Object
}

export const useUserStore= defineStore({
    id:'app-user',

    state:():IUserState=>({
        token:localStorage.getItem('token') || '', //请求token
        username:'', //用户名
        avatar:'', //头像
        permissions:[],//权限
        info:{}  //用户详情
    }),

    getters:{
        getToken():string{
            return this.token;
        },
        getAvatar():string{
            return this.avatar;
        },
        getUsername():string{
            return this.username;
        },
        getPermissions():string[]{
            return this.permissions;
        },
        getUserInfo():Object{
            if(!this.info?.id){
               // console.log(1111111111);
               useUserStore().getUser(); 
            }
            return this.info;
        }

    },

    actions:{
        setToken(token:string){
            localStorage.setItem('token',token);
            this.token=token;
        },
        setAvatar(avatar:string){
            this.avatar=avatar;
        },
        setUsername(name:string){
        
            this.username=name;
        },
        
        setUserInfo(info:Object){
            this.info=info;
        },
        setPermissions(permissions:string[]){
            this.permissions=permissions;
        },
        //async 异步方法使用
         async login(userInfo:Object){
            try {
                const response = await login(userInfo)
                if(response.access_token){
                    this.setToken(response.access_token);
                    this.getUser();
                }
            } catch (error) {
                console.log(error);
            }
        },
        //用户信息
        async getUser(){
            try {
                const response = await user();
                console.log(response);
                this.setUserInfo(response);
                this.setAvatar(response.avatar_url);
                this.setUsername(response.name);
            } catch (error) {
                console.log(error);
            }
        }
    }

})